//
//  LBStatistics.m
//  LBStatistics
//
//  Created by WuShiHai on 19/5/24.
//  Copyright (c) 2019 Lebbay. All rights reserved.
//

#import "LBStatistics.h"

#import <LBFoundation/LBFoundation.h>
#import <LBFoundation/LBService.h>
#import <LBUIKit/LBUIKit.h>

#import <AdSupport/AdSupport.h>

#import <UMCommon/UMConfigure.h>
#import <UMAnalytics/MobClick.h>

#import "LBStatisticsTaskManager.h"
#import "LBStatisticsConfigurationHeader.h"

@implementation LBStatistics

+ (void)gotoStaticPV:(NSString *)page another:(NSDictionary *)d{
    [self gotoStatic:page
           elementid:@"pv"
           eventtype:@"view"
             another:d];
}

+ (void)gotoStatic:(NSString *)elementid eventtype:(NSString *)eventtype another:(NSDictionary *)d{
    [self gotoStatic:[UIApplication displayPageName]
           elementid:elementid
           eventtype:eventtype
             another:d];
}

+ (void)gotoStatic:(NSString *)page elementid:(NSString *)elementid eventtype:(NSString *)eventtype another:(NSDictionary *)d{
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSMutableDictionary *dictionay = [NSMutableDictionary dictionary];
        [dictionay setObject:elementid forKey:@"wmelementid"];
        [dictionay setObject:page forKey:@"wmpagename"];
        [dictionay setObject:eventtype forKey:@"wmeventtype"];
        
        if (d) {
            [dictionay setValuesForKeysWithDictionary:d];
        }
        
        [self gotoStatic:dictionay];
    });
    
}

+ (void)beginLogPageView:(NSString *)pageName {
    [self registerConfigure];
    [MobClick beginLogPageView:pageName];
}

+ (void)endLogPageView:(NSString *)pageName {
    [self registerConfigure];
    [MobClick endLogPageView:pageName];
}

+ (void)gotoStatic:(NSDictionary *)parameters{
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSMutableDictionary *dictionay = [NSMutableDictionary dictionary];
        if (parameters) {
            [dictionay setValuesForKeysWithDictionary:parameters];
        }
        
        //        NSDictionary *systemDictionary = [self wd_systemParam];
        //        if (systemDictionary) {
        //            [dictionay setValuesForKeysWithDictionary:systemDictionary];
        //        }
        //
        //        NSString *host = [NSBundle stringValueWithConfigurationService:LBStatisticsServiceConfiguration
        //                                                                   key:LBStatisticsServiceHostName
        //                                                          defaultValue:@"http://statistic.lebbay.com"];
        //        NSString *statType = [NSBundle stringValueWithConfigurationService:LBStatisticsServiceConfiguration
        //                                                                       key:LBStatisticsServiceStatTypeName
        //                                                              defaultValue:@"LBStatistics"];
        //
        //        NSString *requestUrl = [host stringByAppendingPathComponent:[NSString stringWithFormat:@"wm.js?StatType=%@", statType]];
        //        NSString *paramsString =[self sortJSONString:dictionay];//排序
        //
        //        requestUrl = [requestUrl  stringByAppendingString:paramsString];
        //        requestUrl = [requestUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        //
        //        LBStatisticsTaskData *taskData = [LBStatisticsTaskManager generateOneTaskData:requestUrl params:nil type:LBStatisticsTaskTypeDefault action:nil];
        //        [[LBStatisticsTaskManager manager] addTaskData:taskData];
        
        [self registerConfigure];
        NSString *eventId = [dictionay objectForKey:@"eventId"];
        [MobClick event:eventId attributes:dictionay];
    });
    
}

+ (void)registerConfigure {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *UMengAppKey = LBBundleConfigureStringValue(LBStatisticsServiceConfiguration, LBStatisticsServiceUMengAppKeyName, nil);
        if (UMengAppKey) {
            [UMConfigure initWithAppkey:UMengAppKey channel:@"App Store"];
        }
    });
}

//+ (NSDictionary *)wd_systemParam
//{
//    NSMutableDictionary *dictionay = [NSMutableDictionary dictionary];
//    NSDate *date = [NSDate date];
//    NSString *timestamp = [NSString stringWithFormat:@"%lli", (long long)([date timeIntervalSince1970] * 1000)];
//
//    [dictionay setObject:timestamp forKey:@"wmtimestamp"];
//    [dictionay setObject:AppReleaseVersionNumber() forKey:@"wmappversion"];
//    [dictionay setObject:@"app store" forKey:@"wmappmarket"];
//    [dictionay setObject:@"iOS" forKey:@"wmplatform"];
//    [dictionay setObject:[UIDevice currentDevice].systemVersion forKey:@"wmplatformversion"];
//    [dictionay setObject:[UIDevice currentDevice].model forKey:@"wmmodel"];
//    [dictionay setObject: [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString] forKey:@"wmidfa"];
//    [dictionay setObject:[WDDeviceUtil appDeviceUUID] forKey:@"wmServiceUUID"];
//    NSString *userId = [WDServiceManager userId];
//    if ([userId isKindOfClass:[NSString class]] == YES && userId.length > 0) {
//        [dictionay setObject:[WDServiceManager userId] forKey:@"wid"];
//    }
//
//    return dictionay;
//
//}

+ (NSString *)eventIdFromParameters:(NSDictionary *)parameters{
    NSString *eventType = [self eventStringParameter:parameters
                                                 key:@"eventType"
                                         isUnderline:NO];
    NSString *pageName = [self eventStringParameter:parameters
                                                key:@"pageName"
                                        isUnderline:YES];
    NSString *elementId = [self eventStringParameter:parameters
                                                 key:@"elementId"
                                         isUnderline:YES];
    return [NSString stringWithFormat:@"%@%@%@", eventType, pageName, elementId];
    
}

+ (NSString *)eventStringParameter:(NSDictionary *)parameters
                               key:(NSString *)key
                       isUnderline:(BOOL)isUnderline{
    NSString *parameter = [parameters objectForKey:key];
    if (parameter) {
        return [NSString stringWithFormat:@"%@%@", isUnderline ? @"_" : @"", parameter];
    }
    return @"";
}

//+ (NSString *)sortJSONString:(NSDictionary *)dic{
//    NSString *returnString = @"";
//    NSArray *sortkeyArr = [dic allKeys];
//    NSCountedSet *sets = [[NSCountedSet alloc] initWithArray:sortkeyArr];
//    NSArray *newArray = [[sets allObjects] sortedArrayUsingSelector:@selector(compare:)];
//    for (NSString *key in newArray) {
//        id value=[dic objectForKey:key];
//        NSString *result = @"";
//        if ([value isKindOfClass:[NSDictionary class]] || [value isKindOfClass:[NSArray class]]) {
//            result = [value yy_modelToJSONString];
//        } else {
//            result = value;
//        }
//        returnString = [returnString stringByAppendingString:[NSString stringWithFormat:@"&%@=%@",key,result]];
//    }
//    return returnString;
//}

@end
